﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleData.Infrastructure.Serialization;

namespace SimpleData.ObjectModel.Design
{
	/// <summary>
	/// 
	/// </summary>
	/// <typeparam name="TSettings"></typeparam>
	public abstract class FieldTypeDescriptor<TSettings> : FieldTypeDescriptor
		where TSettings : IFieldTypeConverter, IRuleBuilder, new()
	{

		protected FieldTypeDescriptor( string name )
			: this( new FieldTypeName( name ) )
		{ }

		protected FieldTypeDescriptor( FieldTypeName name )
			: base( name )
		{ }

		public override FieldTypeRule NewTypeRule()
		{
			var rule = base.NewTypeRule();

			DataObjectSerializable<TSettings> serializer = new DataObjectSerializable<TSettings>( new TSettings(), this.CreateStreamer() );
			rule.RuleData = serializer.SerializedValue;

			return rule;
		}

		public override IFieldTypeConverter CreateConverter( FieldDescriptor field )
		{
			return this.GetFrom( field.Rules.FieldType );
		}

		public override IRuleBuilder CreateRuleBuilder( Rule data )
		{
			return this.GetFrom( data );
		}


		private TSettings GetFrom( Rule rule )
		{
			if ( rule == null )
				return default( TSettings );
			else
			{
				DataObjectSerializable<TSettings> serializer = new DataObjectSerializable<TSettings>( rule.RuleData, this.CreateStreamer() );
				return serializer.Value;
			}
		}

		protected virtual IDataObjectStreamer CreateStreamer()
		{
			return new DefaultDataObjectStreamer();
		}
	}
}
